package com.hans.scala.ImplicitConversion

/**
 * 隐式参数
 * Created by Hans on 2014/4/9.
 */
object ParameterExample {
  //上界
  def maxListUpBound[T <: Ordered[T]](elements: List[T]): T = {
    elements match {
      case List() => throw new IllegalArgumentException("empty list!")
      case List(x) => x
      case x :: rest =>
        val maxRest = maxListUpBound(rest)
        if (x > maxRest) x
        maxRest
    }
  }

  //隐式参数
  def maxListUpBound2[T](elements: List[T])(implicit order: T => Ordered[T]): T = elements match {
    case List() => throw new IllegalArgumentException("empty list!")
    case List(x) => x
    case x :: rest =>
      val maxRest = maxListUpBound2(rest)
      //Todo:???
      if (x > maxRest) x
//      if (order(x) > maxRest) x
      else maxRest
  }

  //视图 任何T都好，只要T能被当作Ordered[T]即可；只要能隐式转换，不一定要上界
  def maxListUpBound3[T <% Ordered[T]](elements: List[T]): T = elements match {
    case List() => throw new IllegalArgumentException("empty list!")
    case List(x) => x
    case x :: rest =>
      val maxRest = maxListUpBound2(rest)
      if (x > maxRest) x
      else maxRest
  }

  def main(args: Array[String]) {
    //    println(maxListUpBound(List(5, 2, 7, 6)))
    //        println(maxListUpBound[String](List("5", "2", "7", "6")))//报错
    val list = List("5", "2", "7", "6")
    val result = maxListUpBound2[String](list)
    println(result)
    //    println(maxListUpBound3[String](List("5", "2", "7", "6")))
  }
}
